﻿using Gl_mes.BLL.Mes;
using MesBSW.BLL.Mes;
using MesBSW.DAL.Kingdee;
using MesBSW.DAL.MesDB;
using MesBSW.DAL.MesDTO;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace MesBSW.View.PMC
{
    public partial class LoadingProdForKingdeeFrm : UIPage
    {
        public LoadingProdForKingdeeFrm()
        {
            InitializeComponent();
        }


        #region "内部变量"
        private ProdProcessControler _prod_ctrl = new ProdProcessControler();
        private KingdeeControler _king_ctrl = new KingdeeControler();

        private List<SourceProdProcessDTO> _source_List = new List<SourceProdProcessDTO>();
        #endregion

        #region "控件事件"
        /// <summary>
        /// 查询金蝶系统中的生产用料清单成生MES系统的工单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSearch_Click(object sender, System.EventArgs e)
        {
            DateTime tmpDay = this._prod_ctrl.GetCurrDateTime();
            string kingFilterStr = $"FDOCUMENTSTATUS = 'C' and FPRDORGID in (100153,1402597)";
            if (this.txtProdNumber.Text.Trim().Length <= 0 && this.txtMtoNumber.Text.Trim().Length <= 0)
            {
                kingFilterStr = kingFilterStr + " and FAPPROVEDATE >= '" + tmpDay.AddDays(-10).ToString("yyyy-MM-dd") + "'";
            }
            else
            {
                if (this.txtProdNumber.Text.Trim().Length > 0)
                {
                    kingFilterStr = kingFilterStr + " and fbillno like '%" + this.txtProdNumber.Text.Trim() + "%'";
                }
                if (this.txtMtoNumber.Text.Trim().Length > 0)
                {
                    kingFilterStr = kingFilterStr + " and f_abc_text like '%" + this.txtProdNumber.Text.Trim() + "%'";
                }
            }

            List<PrdPPBom> ppbomList = await this._king_ctrl.SearchPrdPPBomByCondition(kingFilterStr);
            if (ppbomList != null && ppbomList.Count > 0)
            {
                List<string> tmpList = ppbomList.Select(q => q.bill_no).Distinct().ToList();
                List<SourceProdProcess> sourceList = this._prod_ctrl.SearchTargetProdForList(tmpList);
                foreach (var item in ppbomList)
                {
                    Console.WriteLine(item.bill_no);
                    if (item.bill_no.Equals("BSW(TH)PM240600015"))
                    {
                        Console.WriteLine("aaa");
                    }
                    bool isEx = false;
                    if (sourceList != null && sourceList.Count > 0)
                    {
                        var tmpQuery = sourceList.Where(q => q.ProdNumber == item.bill_no);
                        if (tmpQuery != null && tmpQuery.Count() > 0)
                        {
                            isEx = true;
                        }
                    }

                    if (isEx == false)
                    {
                        this._source_List.Add(this.ChangePpbomIntoSourceProd(item));
                    }
                }
            }

            if (this._source_List != null && this._source_List.Count > 0)
            {
                this.UpdateGoodsLength(this._source_List);
                this.dgvProd.DataSource = this.ChangeSourceListToDataTable(this._source_List);
            }
            else
            {
                UIMessageBox.ShowWarning("金蝶系统中没有找到符合条件的工单信息！");
            }
        }


        /// <summary>
        /// 保存工单信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            List<SourceProdProcessDTO> saveList = this.GetSaveListForChoose(this.dgvProd.DataSource as DataTable);
            if (saveList != null && saveList.Count > 0)
            {
                string errStr = this.ChechData(saveList);
                if (string.IsNullOrEmpty(errStr))
                {
                    try
                    {
                        int count = this._prod_ctrl.SaveSourceProdForInputKingdee(saveList);
                        UIMessageBox.ShowSuccess("工单已经全部保存成功！");
                    }
                    catch (Exception ex)
                    {
                        UIMessageBox.ShowError(ex.Message);
                    }
                }
                else
                {
                    UIMessageBox.ShowError(errStr);
                }
            }
            else
            {
                UIMessageBox.ShowWarning("没有任何可以保存的工单信息！");
            }
        }

        /// <summary>
        /// 全选DataTable的所有记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTable tmpDt = this.dgvProd.DataSource as DataTable;
            if (tmpDt != null && tmpDt.Rows.Count > 0)
            {
                foreach (DataRow tmpRow in tmpDt.Rows)
                {
                    tmpRow["is_choose"] = 1;
                }
            }
        }

        /// <summary>
        /// 反选DataTable的所有记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 反选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTable tmpDt = this.dgvProd.DataSource as DataTable;
            if (tmpDt != null && tmpDt.Rows.Count > 0)
            {
                foreach (DataRow tmpRow in tmpDt.Rows)
                {
                    if (tmpRow["is_choose"] != DBNull.Value && int.Parse(tmpRow["is_choose"].ToString()) == 1)
                    {
                        tmpRow["is_choose"] = 0;
                    }
                    else
                    {
                        tmpRow["is_choose"] = 1;
                    }
                }
            }
        }

        /// <summary>
        /// 清空界面数据 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClear_Click(object sender, EventArgs e)
        {
            this.ClearData();
        }

        /// <summary>
        /// 触发快捷键事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadingProdForKingdeeFrm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt == true && e.KeyCode == Keys.C)
            {
                this.btnClear_Click(sender, e);
            }
            else if (e.Alt == true && e.KeyCode == Keys.S)
            {
                this.btnSave_Click(sender, e);
            }
            else if (e.Alt == true && e.KeyCode == Keys.L)
            {
                this.btnSearch_Click(sender, e);
            }

        }
        #endregion

        #region "内部方法"
        /// <summary>
        /// 将金蝶查询出来的生产用料清单转变成工单信息
        /// </summary>
        /// <param name="ppbom"></param>
        /// <returns></returns>
        private SourceProdProcessDTO ChangePpbomIntoSourceProd(PrdPPBom ppbom)
        {
            if (ppbom != null)
            {
                SourceProdProcessDTO resBean = new SourceProdProcessDTO
                {
                    ID = 0,
                    ClientCode = string.IsNullOrEmpty(ppbom.client_number) ? "" : ppbom.client_number,
                    SalerName = string.IsNullOrEmpty(ppbom.saler_name) ? "" : ppbom.saler_name,
                    ProdNumber = string.IsNullOrEmpty(ppbom.bill_no) ? "" : ppbom.bill_no,
                    MoNumber = string.IsNullOrEmpty(ppbom.mo_bill_no) ? "" : ppbom.mo_bill_no,
                    MtoNumber = string.IsNullOrEmpty(ppbom.mto_no) ? "" : ppbom.mto_no,
                    GoodsNumber = string.IsNullOrEmpty(ppbom.material_number) ? "" : ppbom.material_number,
                    GoodsName = string.IsNullOrEmpty(ppbom.material_name) ? "" : ppbom.material_name,
                    GoodsSpe = string.IsNullOrEmpty(ppbom.material_spe) ? "" : ppbom.material_spe,
                    GoodsLength = 0,
                    OrderQty = ppbom.qty,
                    Remark = string.IsNullOrEmpty(ppbom.remark) ? "" : ppbom.remark,
                    OrgNumber = ppbom.prod_orgid.ToString(),
                    DeptId = 13,
                    targetList = new List<TargetProdProcessDTO>()
                    {
                        new TargetProdProcessDTO
                        {
                            ID = 0,
                            ParentID = 0,
                            ClientCode = string.IsNullOrEmpty(ppbom.client_number) ? "" : ppbom.client_number,
                            SalerName = string.IsNullOrEmpty(ppbom.saler_name) ? "" : ppbom.saler_name,
                            ProdNumber = string.IsNullOrEmpty(ppbom.bill_no) ? "" : ppbom.bill_no,
                            MoNumber = string.IsNullOrEmpty(ppbom.mo_bill_no) ? "" : ppbom.mo_bill_no,
                            MtoNumber = string.IsNullOrEmpty(ppbom.mto_no) ? "" : ppbom.mto_no,
                            GoodsNumber = string.IsNullOrEmpty(ppbom.material_number) ? "" : ppbom.material_number,
                            GoodsName = string.IsNullOrEmpty(ppbom.material_name) ? "" : ppbom.material_name,
                            GoodsSpe = string.IsNullOrEmpty(ppbom.material_spe) ? "" : ppbom.material_spe,
                            GoodsLength = 0,
                            OrderQty = ppbom.qty,
                            ProdQty = ppbom.qty,
                            Remark = string.IsNullOrEmpty(ppbom.remark) ? "" : ppbom.remark,
                            ProdStatusID = 13,
                            UrgentStatusID = 8,
                            ErrStatusID = 19,
                            CurrSiteID = 0,
                            OldNumber = ppbom.old_number,
                            OrgNumber = ppbom.prod_orgid.ToString(),
                            DeptId = 13,
                            SiteGroup = new SiteGroupDTO
                            {
                                ID = 1
                            }
                        }
                    }
                };
                return resBean;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 更新每份工单中成品每板可载量
        /// </summary>
        /// <param name="sourceList"></param>
        private void UpdateGoodsLength(List<SourceProdProcessDTO> sourceList)
        {
            if (sourceList != null && sourceList.Count > 0)
            {
                List<string> tmpList = sourceList.Select(q => q.GoodsNumber).Distinct().ToList<string>();
                List<MatInfo> matList = this._prod_ctrl.SearchGoodsInfoForList(tmpList);
                if (matList != null && matList.Count > 0)
                {
                    foreach (var item in sourceList)
                    {
                        string orgid = item.ProdNumber.Contains("TH") ? "1402597" : "100153";
                        var tmpQuery = matList.Where(q => q.mat_number == item.GoodsNumber).Where(a => a.use_ordid == orgid);

                        if (tmpQuery.Count() == 0 && orgid == "100153")
                        {
                            orgid = "BSW";
                            tmpQuery = matList.Where(q => q.mat_number == item.GoodsNumber).Where(a => a.use_ordid == orgid);
                        }

                        if (tmpQuery != null && tmpQuery.Count() > 0 && tmpQuery.First().board_qty > 0)
                        {
                            item.GoodsLength = tmpQuery.First().board_qty;
                            if (item.targetList != null && item.targetList.Count > 0)
                            {
                                foreach (var target in item.targetList)
                                {
                                    target.GoodsLength = tmpQuery.First().board_qty;
                                }
                            }
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 将需要保存的工单信息转化成DataTable
        /// </summary>
        /// <param name="sourceList"></param>
        /// <returns></returns>
        private DataTable ChangeSourceListToDataTable(List<SourceProdProcessDTO> sourceList)
        {
            DataTable resDt = new DataTable();
            resDt.Columns.Add("is_choose", typeof(int));
            resDt.Columns.Add("index", typeof(int));
            resDt.Columns.Add("id", typeof(int));
            resDt.Columns.Add("prod_number", typeof(string));
            resDt.Columns.Add("mo_number", typeof(string));
            resDt.Columns.Add("mto_number", typeof(string));
            resDt.Columns.Add("goods_number", typeof(string));
            resDt.Columns.Add("goods_name", typeof(string));
            resDt.Columns.Add("goods_spe", typeof(string));
            resDt.Columns.Add("goods_length", typeof(decimal));
            resDt.Columns.Add("order_qty", typeof(decimal));
            resDt.Columns.Add("remark", typeof(string));

            if (sourceList != null && sourceList.Count > 0)
            {
                int index = 1;
                foreach (var item in sourceList.OrderBy(q => q.ProdNumber))
                {
                    DataRow addRow = resDt.NewRow();
                    addRow["is_choose"] = 1;
                    addRow["index"] = index;
                    addRow["id"] = item.ID;
                    addRow["prod_number"] = item.ProdNumber;
                    addRow["mo_number"] = item.MoNumber;
                    addRow["mto_number"] = item.MtoNumber;
                    addRow["goods_number"] = item.GoodsNumber;
                    addRow["goods_name"] = item.GoodsName;
                    addRow["goods_spe"] = item.GoodsSpe;
                    addRow["goods_length"] = Math.Round(item.GoodsLength ?? 0, 3);
                    addRow["order_qty"] = Math.Round(item.OrderQty ?? 0, 3);
                    addRow["remark"] = item.Remark;
                    resDt.Rows.Add(addRow);
                    index++;
                }
            }
            return resDt;
        }


        /// <summary>
        /// 从界面列表中提取需要保存的工单
        /// </summary>
        /// <param name="sourceDt"></param>
        /// <returns></returns>
        private List<SourceProdProcessDTO> GetSaveListForChoose(DataTable sourceDt)
        {
            List<SourceProdProcessDTO> resList = new List<SourceProdProcessDTO>();
            if (sourceDt != null && sourceDt.Rows.Count > 0 && this._source_List != null && this._source_List.Count > 0)
            {
                foreach (DataRow itemRow in sourceDt.Rows)
                {
                    if (itemRow["is_choose"] != DBNull.Value && int.TryParse(itemRow["is_choose"].ToString(), out int tmpInt) && tmpInt == 1)
                    {
                        var tmpQuery = this._source_List.Where(q => q.ProdNumber == itemRow["prod_number"].ToString());
                        if (tmpQuery != null && tmpQuery.Count() > 0)
                        {
                            resList.Add(tmpQuery.First());
                        }
                    }
                }
            }
            return resList;
        }


        /// <summary>
        /// 检查将要保存的工单是否存在问题
        /// </summary>
        /// <param name="sourceList"></param>
        /// <returns></returns>
        private string ChechData(List<SourceProdProcessDTO> sourceList)
        {
            string errStr = "";
            if (sourceList != null && sourceList.Count > 0)
            {
                foreach (var item in sourceList)
                {
                    if ((item.GoodsLength ?? 0) <= 0)
                    {
                        errStr = $"工单：{item.ProdNumber} 的每板可载量为0";
                        break;
                    }
                    else if (item.targetList is null || item.targetList.Count <= 0)
                    {
                        errStr = $"工单：{item.ProdNumber} 的目标工单不存在！";
                        break;
                    }
                    else
                    {
                        foreach (var target in item.targetList)
                        {
                            if (target.SiteGroup is null || target.SiteGroup.ID <= 0)
                            {
                                errStr = $"工单：{item.ProdNumber} 的目标工单不存在！";
                                break;
                            }
                        }
                    }
                }
            }
            return errStr;
        }


        /// <summary>
        /// 清空界面数据
        /// </summary>
        private void ClearData()
        {
            this._source_List = new List<SourceProdProcessDTO>();
            this.dgvProd.DataSource = this.ChangeSourceListToDataTable(this._source_List);
        }


        #endregion

    }
}
